#!/bin/bash -x
#this script modify image root user password to root

. /opt/hygon/common.sh

# Function: Check if the device node exists
# Argument 1: Device node path
# Argument 2: Maximum number of retries
# Argument 3: Interval between checks (in seconds)
check_device_exists() {
    local device="$1"
    local max_retries="$2"
    local interval="$3"

    # Initialize retry counter
    local retry_count=0

    # Loop to check if the device node exists
    while [ $retry_count -lt $max_retries ]; do
        if [ -e "$device" ]; then
            echo "$device exists."
            return 0  # Success
        fi
        # Device node does not exist, wait for the specified interval
        sleep $interval
        # Increment the retry counter
        retry_count=$((retry_count + 1))
    done

    # After exceeding the maximum retries, output failure message
    echo "$device does not exist after $max_retries retries."
    return 1  # Failure
}

max_retries=20
interval=1

os_release=$(eval get_os_release)
case $os_release in
    "anolis" | "centos" | "kylin")
        echo "waiting for download anlios image"
        [ ! -f anolisos_8_6_x64_20G_anck_uefi_community_alibase_20220817.vhd ] && wget https://anolis.oss-cn-hangzhou.aliyuncs.com/anolisos_8_6_x64_20G_anck_uefi_community_alibase_20220817.vhd
        qemu-img convert -p -f vpc anolisos_8_6_x64_20G_anck_uefi_community_alibase_20220817.vhd -O qcow2 vm.qcow2
        qemu-img resize /opt/hygon/csv/vm.qcow2 +228G
        echo "modify vm password"
        modprobe nbd max_part=8
        check_device_exists "/dev/nbd0" "$max_retries" "$interval"
        qemu-nbd -c /dev/nbd0 vm.qcow2
        check_device_exists "/dev/nbd0p2" "$max_retries" "$interval"
        mount /dev/nbd0p2 /tmp && chroot /tmp sh -c "echo 'root:root' | chpasswd"
        cp -f sshd_config_anolis   /tmp/etc/ssh/sshd_config
        sleep 1
        umount /tmp && qemu-nbd -d /dev/nbd0
    ;;
    "ubuntu")
        echo "waiting for download ubuntu image"
        [ ! -f focal-server-cloudimg-amd64.img ] &&  wget https://cloud-images.ubuntu.com/focal/current/focal-server-cloudimg-amd64.img
        echo "modify vm password"
        modprobe nbd max_part=8
        check_device_exists "/dev/nbd0" "$max_retries" "$interval"
        qemu-nbd -c /dev/nbd0 focal-server-cloudimg-amd64.img
        check_device_exists "/dev/nbd0p1" "$max_retries" "$interval"
        mount /dev/nbd0p1 /tmp && chroot /tmp sh -c "ssh-keygen -A && echo 'root:root' | chpasswd"
        cp -f sshd_config_ubuntu   /tmp/etc/ssh/sshd_config
        cp -f 60-cloudimg-settings.conf_ubuntu   /tmp/etc/ssh/sshd_config.d/60-cloudimg-settings.conf
        cp -f 01-netcfg.yaml_ubuntu       /tmp/etc/netplan/01-netcfg.yaml
        umount /tmp && qemu-nbd -d /dev/nbd0
        qemu-img resize /opt/hygon/csv/focal-server-cloudimg-amd64.img +228G
        mv focal-server-cloudimg-amd64.img /opt/hygon/csv/vm.qcow2
    ;;
esac

